import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import {
  EditableProTable,
  ProCard,
  ProFormField,
  ProFormRadio,
} from '@ant-design/pro-components';
import {
  Button,
  DatePicker,
  Form,
  Input,
  Modal,
  Radio,
  Tag,
  Select,
  InputNumber,
  message,
  Row,
  Col,
} from 'antd';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import { request } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
type DataSourceType = {};
const defaultData: DataSourceType[] = new Array(2).fill(1).map((_, index) => {
  return {
    id: (Date.now() + index).toString(),
    title: `字段${index}`,
    scantype: '1',
    content: []
  };
});






const ReturnCpm = (props: any) => {
  const { value = [], onChange = (
    value: {
      key: string;
      label: string;
    }[],
  ) => { } } = props;
  return <>
    <div className='flex'>
      {
        value.map((e, i) => {
          return i % 2 == 0 ? <Select placeholder='字段' onChange={(str) => {
            const nv = value.concat([])
            nv[i] = str;
            onChange(nv);
          }}>
            <Option value='a'>字段a</Option>
            <Option value='b'>字段b</Option>
            <Option value='c'>字段c</Option>
          </Select> : <Select placeholder='计算' onChange={(str) => {
            const nv = value.concat([])
            nv[i] = str;
            onChange(nv);
          }}>
            <Option value='+'>加</Option>
            <Option value='-'>减</Option>
            <Option value='*'>乘</Option>
            <Option value='/'>除</Option>
          </Select>
        })
      }
      <PlusOutlined onClick={() => {
        const nv = value.length == 0 ? ['', '', ''] : value.concat(['', ''])
        onChange(nv);
      }} />

    </div>
  </>
}
const DictModal = (props: any, refs: any) => {
  const [form] = Form.useForm();
  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const { setFieldsValue, resetFields } = form;
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>(() => defaultData);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [code, setCode] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [returnDataValue, setreturnDataValue] = useState([])
  const { TextArea } = Input;
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };

  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setCode('');
    resetFields();
    props.callback && props.callback();
  };
  //确定
  const handleOk = () => {
    form
      .validateFields()
      .then((vals) => {
        let Obj = form.getFieldsValue();
        console.log(Obj);
      })
      .catch((info) => { });
  };

  const getDetail = (id: any) => {
    request('/api/dataEncyclopedia/apiCc/getInfo?id=' + id, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        id,
      },
    }).then((res) => {
      setFieldsValue(res?.data);
      showModal();
    });
  };
  useImperativeHandle(refs, () => ({
    init: (id: any, record: any) => {
      if (id) {
        setCode(id);
        getDetail(id);
      } else {
        resetFields();
        showModal();
      }

      // setfileList([]);
    },
  }));
  const columns = [
    {
      title: '字段',
      dataIndex: 'title',
      width: 120
    },
    {
      title: '类型',
      dataIndex: 'scantype',
      width: 120,
      valueEnum: {
        '1': '值',
        '2': '计算'
      },
      valueType: 'select',

    },
    {
      title: '内容',
      dataIndex: 'content',
      renderFormItem: (record, { isEditable }) => {
        console.log(record)
        console.log(editableKeys);
        let index = record.index;
        let item = dataSource[index];
        return <>
          {
            item.scantype == '2' ? (isEditable ? <ReturnCpm value={item.content} onChange={(value) => {
              let dataSourcen = dataSource.concat([]);
              dataSourcen[index]['content'] = value;
              setDataSource(dataSourcen)
            }} /> : <>{JSON.stringify(item.content)}</>) : <Input value={item.content} onChange={(e) => {
              let dataSourcen = dataSource.concat([]);
              dataSourcen[index]['content'] = e.target.value;
              setDataSource(dataSourcen)
            }} />
          }
        </>
      },
      render: (txt, record) => {
        return typeof (record.content) == 'string' ? txt : <span>
          {
            record.content.map((e) => {
              return e;
            })
          }
        </span>
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 130,
      render: (text, record, index, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);


          }}
        >
          编辑
        </a>,
        <a
          key="editable"
          onClick={() => {
            //调用完成事件


          }}
        >
          保存
        </a>,
        // <a
        //   key="delete"
        //   onClick={() => {
        //     const tableDataSource = formRef.current?.getFieldValue('table') as DataSourceType[];
        //     formRef.current?.setFieldsValue({
        //       table: tableDataSource.filter((item) => item.id !== record.id),
        //     });
        //   }}
        // >
        //   删除
        // </a>,
      ],
    },
  ];
  return (
    <Modal
      title={code === '' ? '新增' : '编辑'}
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      centered
      width={1800}
      maskClosable={false}
      bodyStyle={{
        maxHeight: window.innerHeight - 150,
        overflowY: 'auto',
      }}
    >
      <Form form={form} layout="vertical" {...modalLayoutSm}>
        <Row>
          <Col span={12}>
            <Form.Item
              label="API接口地址"
              name="value"
              rules={[{ required: true, message: '请输入API接口地址' }]}
            >
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="请求方式"
              name="method"
              rules={[{ required: true, message: '请选择请求方式' }]}
            >
              <Select>
                <Option value='GET'>GET</Option>
                <Option value='POST'>POST</Option>
                <Option value='DELETE'>DELETE</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              label="返回数据"
            >
              <div>{JSON.stringify(dataSource)}</div>
              <EditableProTable
                columns={columns}
                rowKey="id"
                scroll={{
                  x: 960,
                }}

                value={dataSource}
                onChange={setDataSource}
                recordCreatorProps={{
                  newRecordType: 'dataSource',
                  record: () => ({
                    id: Date.now(),
                  }),
                }}
                editable={{
                  type: 'multiple',
                  editableKeys,
                  actionRender: (row, config, defaultDoms) => {
                    return [defaultDoms.delete];
                  },
                  onValuesChange: (record, recordList) => {
                    setDataSource(recordList);
                  },
                  onChange: setEditableRowKeys,
                }}
              ></EditableProTable>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
const AddMCom = forwardRef(DictModal);

export default AddMCom;
